﻿#include "httpsend.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include <QTimer>
#include "json_trans.h"
#include "common_log.h"
#include "http_log.h"

structJ(AnsMessage,
	mapping(int, code);
mapping(QString, msg);
mapping(QString, data);
prop(&code, &data, &msg);
);

HttpSend::HttpSend(QObject* parent)
	: QObject(parent)
{}

HttpSend::~HttpSend()
{}


int HttpSend::SendGetMsgByHttp(const QString& path, QByteArray& ans)
{
	if (path.isEmpty()) {
		log_error("path error");
		return send_param_error;
	}

	QNetworkAccessManager network;
	QNetworkRequest req(path);
	//req.setRawHeader("Content-Type", "application/json");
	req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
	QNetworkReply* rep = network.get(req);
	if (rep == nullptr) {
		return send_failed;
	}
	if (!rep->isFinished()) {
		QEventLoop p;
		connect(rep, &QNetworkReply::finished, &p, &QEventLoop::quit);
		QTimer::singleShot(3000, &p, &QEventLoop::quit);	// 回复等待时间为3s
		p.exec();
	}

	if (rep->isFinished()) {
		if (rep->error() != QNetworkReply::NoError) {
			log_error("send msg {} error {} ", path.toStdString(), rep->error());
			return -(rep->error());
		}
		ans = rep->readAll();
		return send_ok;
	} else {
		return send_timeout;
	}
}


int HttpSend::SendPostMsgByHttp(const QString& path, const QByteArray& data, QByteArray& ans, bool log)
{
	if (path.isEmpty()) {
		log_error("path error");
		return send_param_error;
	}

	QNetworkAccessManager network;
	QNetworkRequest req(path);
	//req.setRawHeader("Content-Type", "application/json");
	req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
	if (log) {
		log_trace("Send Http Msg: {}: {}", path, data);
		wcs_info("Send Http Msg: {}: {}", path, data);
	}
	QNetworkReply* rep = network.post(req, data);
	if (rep == nullptr) {
		if (log) {
			log_error("Msg Send error");
			wcs_info("****ANS: Msg Send error");
		}
		return send_failed;
	}
	if (!rep->isFinished()) {
		QEventLoop p;
		connect(rep, &QNetworkReply::finished, &p, &QEventLoop::quit);
		QTimer::singleShot(10000, &p, &QEventLoop::quit);	// 回复等待时间为10s
		p.exec();
	}

	if (rep->isFinished()) {
		if (rep->error() != QNetworkReply::NoError) {
			log_error("send msg {} to WCS error {} ", path.toStdString(), rep->error());
			wcs_info("***ANS: ans error:{}", rep->error());
			return -(rep->error());
		}
		ans = rep->readAll();
		if (log) {
			wcs_info("***ANS: {}", ans);
		}
		return send_ok;
	} else {
		if (log) {
			log_error("****http Msg wait timeout");
			wcs_info("***ANS: Msg Send error");
		}
		return send_timeout;
	}
}
